package com.boot.unity.api.filter;

import com.boot.unity.api.common.wrapper.CustomRequestWrapper;
import com.boot.unity.api.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Order(3)
@Component
@ConditionalOnProperty(name = "spring.profiles.active", havingValue = "prod")
public class HttpServletFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AntPathMatcher matcher = new AntPathMatcher();
        String uri = request.getRequestURI();
        if (matcher.match(Constants.API_URI_PREFIX, uri)) {
            CustomRequestWrapper requestWrapper;
            requestWrapper = new CustomRequestWrapper(request);
            if (requestWrapper == null){
                filterChain.doFilter(request, response);
            }else {
                filterChain.doFilter(requestWrapper, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
